package com.zlq.cn.service.un;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.support.retrofit.Retrofit2ConverterFactory;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlq.cn.api.CeicApiResult;
import com.zlq.cn.config.OkhttpConfig;
import com.zlq.cn.entity.Earthquake;
import com.zlq.cn.mapper.un.EarthquakeMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import retrofit2.Call;
import retrofit2.Invocation;
import retrofit2.Retrofit;
import retrofit2.http.GET;
import retrofit2.http.Query;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 地震数据 服务实现类
 * </p>
 *
 * @author zhoucl
 * @since 2023-08-09
 */
@Service
public class EarthquakeService extends ServiceImpl<EarthquakeMapper, Earthquake> {
    private static final MediaType mediaType = MediaType.parse("application/json");

    @Resource
    private CeicApiServiceConfig.CeicApiService ceicApiService;
    @Value("${spring.profiles.active}")
    private String active;

    public Page<Earthquake> list(Page<Earthquake> page, Integer timeType, BigDecimal m, String operator) {
        LambdaQueryChainWrapper<Earthquake> wrapper = super.lambdaQuery();
        if (timeType == null) {
            timeType = 1;
        }
        LocalDateTime now = LocalDateTime.now();
        switch (timeType) {
            case 2:
                wrapper.ge(Earthquake::getOTime, now.minusDays(2));
                break;
            case 3:
                wrapper.ge(Earthquake::getOTime, now.minusDays(7));
                break;
            case 4:
                wrapper.ge(Earthquake::getOTime, now.minusDays(30));
                break;
            default:
                wrapper.ge(Earthquake::getOTime, now.minusDays(1));
                break;
        }
        if (m != null && operator != null) {
            if ("gt".equals(operator)) {
                wrapper.gt(Earthquake::getM, m);
            } else {
                wrapper.lt(Earthquake::getM, m);
            }
        }
        return wrapper.page(page);
    }

//    @SneakyThrows
//    @PostConstruct
//    public void main() {
//        int page = 7;
//        for (int i = 2; i <= page; i++) {
//            Document document = Jsoup.connect("https://zaihaifangyu.cn/category/popularscience/earthquake/page/"+i+"/").get();
////        Document document = Jsoup.parse(FileUtils.readFileToString(new File("C:\\Users\\Administrator\\Desktop\\test.html"), "UTF-8"));
//            List<EarthquakeArticle> earthquakeArticles = new ArrayList<>();
//            for (Element element : document.select(".main li")) {
//                if (element.hasClass("item3")) {
//                    Element aEle = element.selectFirst(".item-images");
//                    String images = StreamEx.of(aEle.select(".item-images-el"))
//                            .map(it -> it.attr("data-original"))
//                            .joining(",");
//                    earthquakeArticles.add(new EarthquakeArticle()
//                            .setUrl(aEle.attr("href"))
//                            .setTitle(element.selectFirst(".item-content .item-title a").text())
//                            .setExcerpt(element.selectFirst(".item-content .item-excerpt").text())
//                            .setImages(images)
//                            .setDate(element.selectFirst(".item-content .item-meta .date").text()));
//                } else if (element.hasClass("item-no-thumb")) {
//                    Element aEle = element.selectFirst(".item-content .item-title a");
//                    earthquakeArticles.add(new EarthquakeArticle()
//                            .setUrl(aEle.attr("href"))
//                            .setTitle(aEle.text())
//                            .setExcerpt(element.selectFirst(".item-content .item-excerpt").text())
//                            .setDate(element.selectFirst(".item-content .item-meta .date").text()));
//                } else {
//                    Element aEle = element.selectFirst(".item-img .item-img-inner");
//                    earthquakeArticles.add(new EarthquakeArticle()
//                            .setUrl(aEle.attr("href"))
//                            .setTitle(element.selectFirst(".item-content .item-title a").text())
//                            .setExcerpt(element.selectFirst(".item-content .item-excerpt").text())
//                            .setImages(aEle.selectFirst("img").attr("data-original"))
//                            .setDate(element.selectFirst(".item-content .item-meta .date").text()));
//                }
//            }
//            earthquakeArticleService.saveBatch(earthquakeArticles);
//        }
//    }

//    @PostConstruct
//    public void xxx() {
//        try {
//            Consumer<CeicApiResult<List<Earthquake>>> saveData = result -> {
//                if (CollectionUtil.isNotEmpty(result.getShuju())) {
//                    super.saveOrUpdateBatch(result.getShuju());
//                }
//            };
//            int num = 4;
//            CeicApiResult<List<Earthquake>> result = ceicApiService.speedsearch(num, 1).execute().body();
//            saveData.accept(result);
//            int page = result.getNum();
//            if (page > 1) {
//                for (int i = 2; i <= page; i++) {
//                    Thread.sleep(5000 + RandomUtil.randomInt(200, 700));
//                    result = ceicApiService.speedsearch(num, i).execute().body();
//                    saveData.accept(result);
//                }
//            }
//            System.out.println("==============");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    // @Scheduled(initialDelay = 60 * 10 * 1000, fixedRate = 60 * 10 * 1000)
    public void sync() {
        if ("prod".equals(active)) {
            try {
                CeicApiResult<List<Earthquake>> result = ceicApiService.speedsearch(1, 1).execute().body();
                if (CollectionUtil.isNotEmpty(result.getShuju())) {
                    super.saveOrUpdateBatch(result.getShuju());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Configuration
    public static class CeicApiServiceConfig {


        interface CeicApiService {

            /**
             * 获取地震数据
             *
             * @param num 1：最近24小时，2：最近48小时，3：最近7天，4：最近30天
             */
            @GET("/ajax/speedsearch")
            Call<CeicApiResult<List<Earthquake>>> speedsearch(@Query("num") int num,
                                                              @Query("page") int page);
        }

        @Bean("ceicApiInterceptor")
        public Interceptor ceicApiInterceptor() {
            return chain -> {
                Request request = chain.request();
                Invocation invocation = request.tag(Invocation.class);
                Class<?> aClass = Optional.ofNullable(invocation).map(Invocation::method).map(Method::getDeclaringClass).orElse(null);
                boolean assignableFrom = aClass != null && aClass.isAssignableFrom(CeicApiService.class);
                if (assignableFrom) {
                    Response response = chain.proceed(request);
                    String body = response.body().string().replaceAll("\\(", "").replaceAll("\\)", "");
                    return response.newBuilder()
                            .body(ResponseBody.create(body, mediaType))
                            .build();
                }
                return chain.proceed(request);
            };
        }

        @Bean("ceicApiService")
        public CeicApiService ceicApiService() {
            return new Retrofit.Builder()
                    .baseUrl("http://www.ceic.ac.cn")
                    .client(OkhttpConfig.okHttpClient)
                    .addConverterFactory(Retrofit2ConverterFactory.create())
                    .build()
                    .create(CeicApiService.class);
        }
    }
}
